package com.zhixun.mobile.modules.edu.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.boxin.ims.modules.education.entity.Binding;
import com.boxin.ims.modules.education.entity.Classhour;
import com.boxin.ims.modules.education.entity.Educomment;
import com.boxin.ims.modules.education.entity.Homework;
import com.boxin.ims.modules.education.entity.Notice;
import com.boxin.ims.modules.education.entity.Syllabus;
import com.boxin.ims.modules.education.service.BindingService;
import com.boxin.ims.modules.education.service.ClasshourService;
import com.boxin.ims.modules.education.service.EducommentService;
import com.boxin.ims.modules.education.service.HomeworkService;
import com.boxin.ims.modules.education.service.NoticeService;
import com.boxin.ims.modules.education.service.SyllabusService;
import com.boxin.ims.modules.wechat.entity.WechatMember;
import com.boxin.ims.modules.wechat.service.WechatMemberService;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.zhixun.mobile.common.utils.EncryptUtils;
import com.zhixun.mobile.common.utils.StringUtils;
import com.zhixun.mobile.modules.base.web.BaseController;
import com.zhixun.mobile.modules.edu.service.EduService;
import com.zhixun.mobile.modules.edu.utils.BindingUtils;
import com.zhixun.mobile.sys.utils.AssertUtils;
import com.zhixun.mobile.sys.utils.SessionMemberUtils;


@Controller
@RequestMapping(value = "/edu/usercentraList")
public class UserCentraListController  extends BaseController {
	
	
	@Autowired
	WechatMemberService wechatMemberService;
	
	@Autowired
	private NoticeService noticeService;
	
	@Autowired
	private BindingService bindingService;
	
	@Autowired
	private SyllabusService syllabusService;
	
	@Autowired
	private ClasshourService classhourService;
	
	@Autowired
	private EduService eduService;
	
	@Autowired
	private HomeworkService homeworkService;
	
	@Autowired
	private EducommentService educommentService;
	
	//TODO 公告
	@RequestMapping(value = "notice")
	public String notice(HttpServletRequest request,
			HttpServletResponse response, Model model,
			RedirectAttributes redirectAttributes) {

		String style = request.getParameter("style");

		style = this.isStyle(style);

		String id = request.getParameter("uid"); // userId
		String wechatId = request.getParameter("wechatId"); // OpenId

		model.addAttribute("wechatId", wechatId);
		model.addAttribute("uid", id);
		request.setAttribute("style", style);
		model.addAttribute("topage", "notice");
		
		User user = new User();
		  user.setId(Long.parseLong(id));
		
		WechatMember member = this.isLogin(request, id);
		
		Binding binding=new Binding();
		binding.setWechatMember(member);
		binding.setUser(user);
		BindingUtils.getBindingList(binding);
		
		
		List<Binding> bindingList= BindingUtils.getBindingList(binding);
		model.addAttribute("bindingList", bindingList);
		
	     Binding temp=(Binding) request.getSession().getAttribute("binding_id");
	     if(temp==null){
	      if(bindingList.size()>0){
	       temp=bindingList.get(0);
	      }
	      SessionMemberUtils.addSessionValue(request, "binding_id", temp);
	     }
		model.addAttribute("binding", temp);
		


		if (AssertUtils.notNull(member)) {
			
			Notice notice=new Notice();
			notice.setUser(user);
			List<Notice>  schoolNoticeList=noticeService.getSchoolNoticeByUserId(notice);
			
			if(temp!=null&&!temp.getState().equals("0")){
				
				notice.setGrade(temp.getStudent().getGrade());
				List<Notice>  gradeNoticeList=noticeService.getGradeNoticeByUserId(notice);

				model.addAttribute("gradeNoticeList", gradeNoticeList);
			}
			
			
			model.addAttribute("schoolNoticeList", schoolNoticeList);
			
			request.setAttribute("wechatMember", member);
			return "modules/edu/themes/" + style + "/notice";
		}else {

			Map<String, Object> map = this.beforeLogin(id, wechatId);

			model.addAttribute("login_mobile", map.get("mobile"));
			model.addAttribute("pwd", map.get("pwd"));

			return "modules/edu/themes/" + style + "/login";
		}

	}
	
	
	//TODO 改变缓存
		@RequestMapping(value = "changeCache")
		public String changeCache(HttpServletRequest request,
				HttpServletResponse response, Model model,
				RedirectAttributes redirectAttributes) {

			String style = request.getParameter("style");

			style = this.isStyle(style);

			String id = request.getParameter("uid"); // userId
			String wechatId = request.getParameter("wechatId"); // OpenId

			model.addAttribute("wechatId", wechatId);
			model.addAttribute("uid", id);
			request.setAttribute("style", style);
			model.addAttribute("topage", "notice");
			
			String binding_id=request.getParameter("binding_id");
			
			WechatMember member = this.isLogin(request, id);
			
			User user = new User();
			  user.setId(Long.parseLong(id));

			if (AssertUtils.notNull(member)) {
				
				Binding binding=bindingService.getBindingById(Long.parseLong(binding_id));
				SessionMemberUtils.addSessionValue(request, "binding_id", binding);

				
				return "redirect:/edu/bind?uid="+id+"&wechatId="+wechatId+"&style="+style;
			}else {

				Map<String, Object> map = this.beforeLogin(id, wechatId);

				model.addAttribute("login_mobile", map.get("mobile"));
				model.addAttribute("pwd", map.get("pwd"));

				return "modules/edu/themes/" + style + "/login";
			}

		}
	
		
		//TODO 查看
				@RequestMapping(value = "viewNotice")
				public String viewNotice(HttpServletRequest request,
						HttpServletResponse response, Model model,
						RedirectAttributes redirectAttributes) {
					
					
					System.out.println("aaa");
					String style = request.getParameter("style");

					style = this.isStyle(style);

					String id = request.getParameter("uid"); // userId
					String wechatId = request.getParameter("wechatId"); // OpenId

					model.addAttribute("wechatId", wechatId);
					model.addAttribute("uid", id);
					request.setAttribute("style", style);
					model.addAttribute("topage", "notice");
					
					String notice_id=request.getParameter("notice_id");
					
					WechatMember member = this.isLogin(request, id);
					
					User user = new User();
					  user.setId(Long.parseLong(id));

					if (AssertUtils.notNull(member)) {
						
						Notice notice=noticeService.getNoticeById(Long.parseLong(notice_id));
						
						model.addAttribute("notice", notice);
						
						return "modules/edu/themes/" + style + "/viewNotice";
					}else {

						return "redirect:/edu/bind?uid="+id+"&wechatId="+wechatId+"&style="+style;
					}

				}
				
				//TODO 查看
				@RequestMapping(value = "viewSyllabus")
				public String viewSyllabus(HttpServletRequest request,
						HttpServletResponse response, Model model,
						RedirectAttributes redirectAttributes) {
					
					
					String style = request.getParameter("style");

					style = this.isStyle(style);

					String id = request.getParameter("uid"); // userId
					String wechatId = request.getParameter("wechatId"); // OpenId

					model.addAttribute("wechatId", wechatId);
					model.addAttribute("uid", id);
					request.setAttribute("style", style);
					model.addAttribute("topage", "notice");
					
					User user = new User();
					  user.setId(Long.parseLong(id));
					WechatMember member = this.isLogin(request, id);	
					
					Binding binding=new Binding();
					binding.setWechatMember(member);
					binding.setUser(user);
					BindingUtils.getBindingList(binding);
					
					
					List<Binding> bindingList= BindingUtils.getBindingList(binding);
					model.addAttribute("bindingList", bindingList);
					
					Binding temp=(Binding) request.getSession().getAttribute("binding_id");
					if(temp==null){
						if(bindingList.size()>0){
							temp=bindingList.get(0);
						}
						SessionMemberUtils.addSessionValue(request, "binding_id", temp);
					}
					
					if(temp==null){
						model.addAttribute("errorMessage", "您还没有绑定您的孩子");	
						return "modules/edu/themes/" + style + "/error";
					}else if(temp.getState().equals("0")){
						model.addAttribute("errorMessage", "您绑定孩子孩子的申请还没通过");	
						return "modules/edu/themes/" + style + "/error";
					}
					
					

					if (AssertUtils.notNull(member)) {
						
						
						Syllabus syllabus=new Syllabus();
						syllabus.setUser(user);
						syllabus.setGrade(temp.getStudent().getGrade());
						
						List<Syllabus> syllabusList=syllabusService.findByUserId(syllabus);
						
						List<List<Syllabus>> list=new ArrayList<List<Syllabus>>();
						
						Classhour classhour=new Classhour();
						classhour.setUser(user);
						List<Classhour> classhours=classhourService.getClasshourListByUserId(classhour);
						
						Map<String, Object> params =new HashMap<String, Object>();
						params.put("user_id", id);
						params.put("class_id", temp.getStudent().getGrade().getId());
						List<Map<String, Object>> maxList=  eduService.getSyllabusMaxWeek(params);
						
						String max="";
						if(maxList.get(0).get("max")!=null){
							max=maxList.get(0).get("max").toString();
						}else{
							model.addAttribute("errorMessage", "懒惰的园长没有添加信息表");
							return "modules/edu/themes/" + style + "/error";
						}
						
						for (int i = 1; i <=Integer.parseInt(max); i++) {
							List<Syllabus> list2=new ArrayList<Syllabus>();
							for (int j = 1; j <= classhours.size(); j++) {
								for (int k = 0; k < syllabusList.size(); k++) {
									if(syllabusList.get(k).getWeek()==i&&syllabusList.get(k).getClasshour().getSort()==j){
										list2.add(syllabusList.get(k));
										break;
									}
									syllabusList.get(j).getClasshour().getSort();
								}
							}
							list.add(list2);
						}
						
						
						
						model.addAttribute("list", list);
						
						return "modules/edu/themes/" + style + "/viewSyllabus";
					}else {

						return "redirect:/edu/bind?uid="+id+"&wechatId="+wechatId+"&style="+style;
					}

				}
				
				
				//TODO 查看今天作业
				@RequestMapping(value = "viewHomeWorkByToday")
				public String viewHomeWorkByToday(HttpServletRequest request,
						HttpServletResponse response, Model model,
						RedirectAttributes redirectAttributes) {
					
					
					String style = request.getParameter("style");

					style = this.isStyle(style);

					String id = request.getParameter("uid"); // userId
					String wechatId = request.getParameter("wechatId"); // OpenId

					model.addAttribute("wechatId", wechatId);
					model.addAttribute("uid", id);
					request.setAttribute("style", style);
					model.addAttribute("topage", "notice");
					
					
					WechatMember member = this.isLogin(request, id);
					
					User user = new User();
					  user.setId(Long.parseLong(id));
					  
					  Binding binding=new Binding();
						binding.setWechatMember(member);
						binding.setUser(user);
						BindingUtils.getBindingList(binding);
						
					  List<Binding> bindingList= BindingUtils.getBindingList(binding);
					     model.addAttribute("bindingList", bindingList);
					     
					     if(bindingList.size()==0){
					    	 model.addAttribute("errorMessage", "您还没有绑定您的孩子");
							return "modules/edu/themes/" + style + "/error";
					     }
					     
					     Binding temp=(Binding) request.getSession().getAttribute("binding_id");
					     if(temp==null){
					      if(bindingList.size()>0){
					       temp=bindingList.get(0);
					      }
					      SessionMemberUtils.addSessionValue(request, "binding_id", temp);
					     }
					    if(temp!=null){
					    	if(temp.getState().equals("0")){
					    		model.addAttribute("errorMessage", "您绑定孩子孩子的申请还没通过");	
					    		return "modules/edu/themes/" + style + "/error";
					    	}
					    } 
					if (AssertUtils.notNull(member)) {
						
						List<Homework> homeworks=homeworkService.getTodayHomeworkById(Long.parseLong(id), temp.getStudent().getGrade().getId());
						
						model.addAttribute("homeworks", homeworks);
						
						return "modules/edu/themes/" + style + "/viewHomeWorkByToday";
					}else {
						return "redirect:/edu/bind?uid="+id+"&wechatId="+wechatId+"&style="+style;
					}

				}
				
				
				
				//TODO 查看作业
				@RequestMapping(value = "viewHomeWork")
				public String viewHomeWork(HttpServletRequest request,
						HttpServletResponse response, Model model,
						RedirectAttributes redirectAttributes) {
					
					
					String style = request.getParameter("style");

					style = this.isStyle(style);

					String id = request.getParameter("uid"); // userId
					String wechatId = request.getParameter("wechatId"); // OpenId

					model.addAttribute("wechatId", wechatId);
					model.addAttribute("uid", id);
					request.setAttribute("style", style);
					model.addAttribute("topage", "notice");
					
					
					WechatMember member = this.isLogin(request, id);
					
					User user = new User();
					  user.setId(Long.parseLong(id));
					  
					  Binding binding=new Binding();
						binding.setWechatMember(member);
						binding.setUser(user);
						BindingUtils.getBindingList(binding);
						
					  
					  List<Binding> bindingList= BindingUtils.getBindingList(binding);
					     model.addAttribute("bindingList", bindingList);
					     
					     if(bindingList.size()==0){
					    	 model.addAttribute("errorMessage", "您还没有绑定您的孩子");
							return "modules/edu/themes/" + style + "/error";
					     }
					     
					     Binding temp=(Binding) request.getSession().getAttribute("binding_id");
					     if(temp==null){
					      if(bindingList.size()>0){
					       temp=bindingList.get(0);
					      }
					      SessionMemberUtils.addSessionValue(request, "binding_id", temp);
					     }
					     if(temp!=null){
						    	if(temp.getState().equals("0")){
						    		model.addAttribute("errorMessage", "您绑定孩子孩子的申请还没通过");	
						    		return "modules/edu/themes/" + style + "/error";
						    	}
						    } 
					if (AssertUtils.notNull(member)) {
						
						Map<String, Object> params =new HashMap<String,Object>();
						
						params.put("user_id", Long.parseLong(id));
						params.put("class_id", temp.getStudent().getGrade().getId());
						
						List<Map<String, Object>> homeworks=eduService.getHomeWorkByDate(params);
						
						List<List<Map<String, Object>>> homeworkList=new ArrayList<List<Map<String, Object>>>();
						
						List<Map<String, Object>> date=eduService.selectHomeWorkDate(params);
						
						for (int i = 0; i < date.size(); i++) {
							List<Map<String, Object>> temp1=new ArrayList<Map<String, Object>>();
							for (int j = 0; j < homeworks.size(); j++) {
								if(homeworks.get(j).get("date").equals(date.get(i).get("date"))){
									temp1.add(homeworks.get(j));
								}
							}
							homeworkList.add(temp1);
						}
						
						model.addAttribute("homeworkList", homeworkList);
						model.addAttribute("date", date);
						
						return "modules/edu/themes/" + style + "/viewHomeWork";
					}else {
						return "redirect:/edu/bind?uid="+id+"&wechatId="+wechatId+"&style="+style;
					}
				}
				
				
				//TODO 查看作业
				@RequestMapping(value = "viewHomeWorkAndComment")
				public String viewHomeWorkAndComment(HttpServletRequest request,
						HttpServletResponse response, Model model,
						RedirectAttributes redirectAttributes) {
					
					
					String style = request.getParameter("style");

					style = this.isStyle(style);

					String id = request.getParameter("uid"); // userId
					String wechatId = request.getParameter("wechatId"); // OpenId

					model.addAttribute("wechatId", wechatId);
					model.addAttribute("uid", id);
					request.setAttribute("style", style);
					model.addAttribute("topage", "notice");
					
					String homework_id	=request.getParameter("homework_id");
					
					
					WechatMember member = this.isLogin(request, id);
					
					User user = new User();
					  user.setId(Long.parseLong(id));
					  
					  Binding binding=new Binding();
						binding.setWechatMember(member);
						binding.setUser(user);
						BindingUtils.getBindingList(binding);
					  
					  List<Binding> bindingList= BindingUtils.getBindingList(binding);
					     model.addAttribute("bindingList", bindingList);
					     
					     if(bindingList.size()==0){
					    	 model.addAttribute("errorMessage", "您还没有绑定您的孩子");
							return "modules/edu/themes/" + style + "/error";
					     }
					     
					     Binding temp=(Binding) request.getSession().getAttribute("binding_id");
					     if(temp==null){
					      if(bindingList.size()>0){
					       temp=bindingList.get(0);
					      }
					      SessionMemberUtils.addSessionValue(request, "binding_id", temp);
					     }
					     if(temp!=null){
						    	if(temp.getState().equals("0")){
						    		model.addAttribute("errorMessage", "您绑定孩子孩子的申请还没通过");	
						    		return "modules/edu/themes/" + style + "/error";
						    	}
						    } 
					if (AssertUtils.notNull(member)) {
						Homework homework=homeworkService.getHomeworkById(Long.parseLong(homework_id));
						
						Educomment educomment= educommentService.getEducommentByHomeworkId(Long.parseLong(homework_id),temp.getStudent().getId());
						 
						 
						model.addAttribute("homework", homework);
						model.addAttribute("educomment", educomment);
						
						return "modules/edu/themes/" + style + "/viewHomeWorkAndComment";
					}else {
						return "redirect:/edu/bind?uid="+id+"&wechatId="+wechatId+"&style="+style;
					}
				}
				
				
				
				//TODO 查看今天作业
				@RequestMapping(value = "bindingManage")
				public String bindingManage(HttpServletRequest request,
						HttpServletResponse response, Model model,
						RedirectAttributes redirectAttributes) {
					
					
					String style = request.getParameter("style");

					style = this.isStyle(style);

					String id = request.getParameter("uid"); // userId
					String wechatId = request.getParameter("wechatId"); // OpenId

					model.addAttribute("wechatId", wechatId);
					model.addAttribute("uid", id);
					request.setAttribute("style", style);
					model.addAttribute("topage", "notice");
					
					
					WechatMember member = this.isLogin(request, id);
					
					User user = new User();
					  user.setId(Long.parseLong(id));
					  
					  Binding binding=new Binding();
						binding.setWechatMember(member);
						binding.setUser(user);
						BindingUtils.getBindingList(binding);
					  
					  List<Binding> bindingList= BindingUtils.getBindingList(binding);
					     model.addAttribute("bindingList", bindingList);
					     
					     
					     Binding temp=(Binding) request.getSession().getAttribute("binding_id");
					     if(temp==null){
					      if(bindingList.size()>0){
					       temp=bindingList.get(0);
					      }
					      SessionMemberUtils.addSessionValue(request, "binding_id", temp);
					     }
					if (AssertUtils.notNull(member)) {
						
						return "modules/edu/themes/" + style + "/bindingManage";
					}else {
						return "redirect:/edu/bind?uid="+id+"&wechatId="+wechatId+"&style="+style;
					}

				}
				
				
				//TODO 查看今天作业
				@RequestMapping(value = "toBindingManage")
				public String toBindingManage(HttpServletRequest request,
						HttpServletResponse response, Model model,
						RedirectAttributes redirectAttributes) {
					
					
					String style = request.getParameter("style");

					style = this.isStyle(style);

					String id = request.getParameter("uid"); // userId
					String wechatId = request.getParameter("wechatId"); // OpenId

					model.addAttribute("wechatId", wechatId);
					model.addAttribute("uid", id);
					request.setAttribute("style", style);
					model.addAttribute("topage", "notice");
					
					
					WechatMember member = this.isLogin(request, id);
					
					User user = new User();
					  user.setId(Long.parseLong(id));
					  
					  Binding binding=new Binding();
					  binding.setUser(user);
						binding.setWechatMember(member);
						BindingUtils.getBindingList(binding);
					  
					  List<Binding> bindingList= BindingUtils.getBindingList(binding);
					     model.addAttribute("bindingList", bindingList);
					     
					     
					     Binding temp=(Binding) request.getSession().getAttribute("binding_id");
					     if(temp==null){
					      if(bindingList.size()>0){
					       temp=bindingList.get(0);
					      }
					      SessionMemberUtils.addSessionValue(request, "binding_id", temp);
					     }
					if (AssertUtils.notNull(member)) {
						List<Binding> bindings= bindingService.getBindingByMember(binding);
						
						model.addAttribute("bindings", bindings);
						
						bindingService.getBindingByMember(binding);
						return "modules/edu/themes/" + style + "/toBindingManage";
					}else {
						return "redirect:/edu/bind?uid="+id+"&wechatId="+wechatId+"&style="+style;
					}

				}
	/**
	 * 判断用户是否登陆
	 * 
	 * @return WechatMember null 没有登陆 ；
	 */
	//TODO 判断用户是否登陆
	public WechatMember isLogin(HttpServletRequest request, String uid) {

		WechatMember member = SessionMemberUtils.getSessionMemberByUserId(
				request, uid);

		if (AssertUtils.notNull(member)) {
			member = wechatMemberService.get(member.getId());
		}

		return member;
	}
	
	/**
	 * 判断商家样式
	 */
	public String isStyle(String style) {
		String string = "";

		if (AssertUtils.isNullOrEmpty(style)) {
			string = "default";
			// string = "ShiShangHong" ;

		} else {
			string = style;
		}

		return "YouErJiaoYu";
	}
	
	
	/**
	 * 跳到登陆页面前根据 uid 和 wechatID 查询 会员。 如果有， 返回 手机号
	 */
	public Map<String, Object> beforeLogin(String uid, String wechatId) {
		Map<String, Object> map = new HashMap<String, Object>();
		String mobile = "";
		String pwd = "";

		User user = new User();

		user.setId(Long.parseLong(uid));

		WechatMember wechatMember = wechatMemberService.getByWechatMemberId(
				user, wechatId);

		if (AssertUtils.notNull(wechatMember)) {

			mobile = wechatMember.getMobile();

			// 是否需要初始化密码
			if (StringUtils.isEmpty(wechatMember.getPassword())
					|| wechatMember.isRandomPassword()) {
				pwd = com.thinkgem.jeesite.common.utils.StringUtils
						.getRandPassword();
				String enpwd = EncryptUtils.MD5EncodeString(pwd);
				wechatMember.setPassword(enpwd);
				wechatMember.setIsRandomPassword(true);

				wechatMemberService.save(wechatMember);
			}

			if (AssertUtils.isNullOrEmpty(pwd)) {
				pwd = null;
			}

			map.put("mobile", mobile);
			map.put("pwd", pwd);
		}

		return map;
	}
	
	
	
	
}
